package com.fablesoft.projectdatacollect.services;

import android.app.ProgressDialog;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.VersionResponse;
import com.fablesoft.projectdatacollect.http.DownloadListener;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.RequestData;
import com.fablesoft.projectdatacollect.http.RequestDownload;
import com.fablesoft.projectdatacollect.util.CheckUpdateVersion;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.JyCustomDialog;

import java.io.File;

public class VersionUpdateService extends Service {

    private static final int CHECK_UPDATE_CODE = 0X1001;
    private static final int DOWNLOAD_SUCCESS_CODE = 0X1002;
    private static final int DOWNLOAD_FAIL_CODE = 0X1003;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("sglei-update", "onStartCommand flags = " + flags + ", startId = " + startId);
        checkUpdate();
        return START_NOT_STICKY;
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CHECK_UPDATE_CODE:
                    final VersionResponse version = (VersionResponse) msg.obj;
                    if (version == null || version.getData() == null || !CheckUpdateVersion.isUpdate(version.getData().getVersionNo())) {
                        return;
                    }
                    final JyCustomDialog dialog = new JyCustomDialog(VersionUpdateService.this).createTwoButtonDialog();
                    dialog.setMessage("发现新版本，是否下载并更新？")
                            .setLeftBtnClick(R.string.bt_cancel, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog.cancel();
                                }
                            }).setRightBtnClick(R.string.bt_download, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            downloadApk(version.getData().getDownloadUrl());
                            dialog.cancel();
                        }
                    }).setSystemType().show();
                    break;
                case DOWNLOAD_SUCCESS_CODE:
                    Bundle data = msg.getData();
                    File apkfile = new File(data.getString("path"), data.getString("name"));
                    if (!apkfile.exists()) {
                        return;
                    }
                    // 通过Intent安装APK文件
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Uri path = Uri.parse("file://" + apkfile.toString());
                    if (Build.VERSION.SDK_INT >= 24) {
                        path = FileProvider.getUriForFile(VersionUpdateService.this, VersionUpdateService.this.getPackageName() + ".opener.provider", apkfile);
                    }
                    intent.setDataAndType(path, "application/vnd.android.package-archive");
                    VersionUpdateService.this.startActivity(intent);
                    android.os.Process.killProcess(android.os.Process.myPid());
                    stopSelf();
                    break;
                case DOWNLOAD_FAIL_CODE:
                    Toast.makeText(VersionUpdateService.this, "文件下载失败，请检查网络设置", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    private void checkUpdate() {

        new RequestData(Config.APP_CHECKUPDATE_URL + "?applicationType=2", VersionResponse.class, new HttpListener() {
            @Override
            public void onRequestFinish(BaseResponse response) {
                Message msg = mHandler.obtainMessage();
                msg.obj = response;
                msg.what = CHECK_UPDATE_CODE;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onNotLogin(BaseResponse response) {
            }
        }).getVersionInfo();
    }

    private void downloadApk(String url) {
        final int MAX_PROGRESS = 100;
        final ProgressDialog progressDialog =
                new ProgressDialog(VersionUpdateService.this);
        progressDialog.setProgress(0);
        progressDialog.setTitle("正在下载...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(MAX_PROGRESS);
        progressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        progressDialog.show();
        RequestDownload.getInstance().download(Config.BASE + "/" + url, CommonUtils.APK_SAVE_PATH, new DownloadListener() {
            @Override
            public void onDownloadSuccess(String filepath, String filename) {
                progressDialog.dismiss();
                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("path", filepath);
                bundle.putString("name", filename);
                msg.setData(bundle);
                msg.what = DOWNLOAD_SUCCESS_CODE;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onDownloading(final int progress) {
                if (progress >= 0 && progress <= 100) {
                    progressDialog.setProgress(progress);
                }
            }

            @Override
            public void onDownloadFailed() {
                progressDialog.dismiss();
            }
        });

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
